interface ListNode {
	val: number;
	next: ListNode | null;
}

export const getInputs = () => {
	const buildList = (arr: number[]) => {
		let tmp = null;
		for (let i = arr.length - 1; i >= 0; i--) {
			tmp = {
				val: arr[i],
				next: tmp,
			};
		}
		return tmp;
	};

	return [
		[buildList([1, 2, 3, 4, 5]), 2],
		[buildList([0, 1, 2]), 4],
		[buildList([1]), 0],
		[buildList([1]), 1],
	];
};

export default function (head: ListNode | null, k: number): ListNode | null {
	if (!head || k === 0) return head;

	let next: ListNode | null = head;
	let size = 0;
	let tail = head;
	while (!!next) {
		size++;
		tail = next;
		next = next.next;
	}

	let offset = size - (k % size);

	let newTail: ListNode | null = head;
	while (--offset > 0) {
		newTail = newTail!.next;
	}

	const newHead = newTail!.next;
	if (!newHead) return head;

	newTail!.next = null;
	tail!.next = head;

	return newHead;
}
